import type { ILessonResult } from "@/pages/lowPricedCourse/trialCourseHome/courseList/index.vue";
import type { IResult, IListenTrainingResult } from "@/pages/lowPricedCourse/listeningPractice/listenTraining/index.vue";
import API from "@/api";

export const requestNecessaryData = (sectionId: number): Promise<ILessonResult> => {
  return new Promise((resolve, reject) => {
    API.listenTrainData({ section_id: sectionId })
      .then((res) => {
        let questions = (res as IResult).listen;
        let isRelearn = questions.every((item) => {
          return item.is_select === 1;
        });
        if (isRelearn) {
          questions.forEach((element) => {
            element.is_select = 0;
            element.option.forEach((element) => {
              element.select_this = 0;
            });
          });
        }

        var currentIndex = -1;

        for (var i = 0; i < questions.length; i++) {
          if (!questions[i].is_select) {
            currentIndex = i;
            break;
          }
        }

        let data: IListenTrainingResult = {
          isRelearn: isRelearn,
          isNeedLaunchPage: isRelearn || currentIndex === 0,
          data: { listen: questions, currentQuestionIndex: currentIndex },
        };
        resolve(data);
      })
      .catch((err) => {
        debugger
        reject(err);
      });
  });
};
